# 颜色定义
RED='\033[31m'
CYAN='\033[36m'
YELLOW='\033[33m'
GREEN='\033[32m'
RESET='\033[0m'

# 参数校验
if [ -z "$1" ]; then
  echo -e "${RED}Error: Please specify a directory.${RESET}"
  echo -e "${YELLOW}Usage: $0 <directory>${RESET}"
  exit 1
fi

# 规范化目录路径
DIR=$(realpath "$1" 2>/dev/null || echo "$1" | sed 's|/$||')
echo -e "${CYAN}Scanning directory: ${YELLOW}$DIR${RESET}"

# 排除目录列表（匹配任意层级的同名目录）
EXCLUDE_DIRS=("node_modules" "logs" "third" "pids" ".git")
echo -e "${CYAN}Excluded directories: ${YELLOW}${EXCLUDE_DIRS[*]}${RESET}"

# 排除文件模式
EXCLUDE_FILES=("*.out" "*.jpg" "*.db" "*.xlsx" "json.hpp" "httplib.h" "*.log" "pack*.json" "*.ico")
echo -e "${CYAN}Excluded file patterns: ${YELLOW}${EXCLUDE_FILES[*]}${RESET}"

# 构建find命令参数数组
find_args=()

# 添加目录排除条件（匹配任意层级的目录）
for dir in "${EXCLUDE_DIRS[@]}"; do
  find_args+=(-path "*/$dir" -prune -o)
done

# 添加文件排除条件
for file in "${EXCLUDE_FILES[@]}"; do
  find_args+=(! -name "$file")
done

# 执行查找并统计
total_lines=0
while IFS= read -r file; do
  lines=$(wc -l < "$file")
  printf "${GREEN}%6d${RESET} ${YELLOW}%s${RESET}\n" "$lines" "$file"
  ((total_lines += lines))
done < <(find "$DIR" "${find_args[@]}" -type f)

# 输出总行数
echo -e "${CYAN}Total lines of code: ${GREEN}$total_lines${RESET}"